from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.template import RequestContext
from django.core.context_processors import csrf
from .models import User
from .forms import UploadFileForm
import sys
import os
#sys.path.append('/home/cgf/caffeLabUsing/examples')
#import caffeRecongination

# Create your views here.
def index(request):
    #return HttpResponse("index")
    #return render(request, 'FetchMe/index.html')
    return JsonResponse({'content':'FetchMe'})

def login(request):
    if request.method == 'GET':
        loginResponse = {'isLogin' : False, 'csrfToken' : 0,}
        userNameStr = request.GET.get('userName')
        userPwdStr = request.GET.get('userPwd')
        version = request.GET.get('version')
        user = User.objects.filter(userName=userNameStr, userPwd=userPwdStr)
        isUser = len(user)
        if(isUser):
            #return HttpResponse("login success")
            csrfToken = {}
            csrfToken.update(csrf(request))
            loginResponse['isLogin'] = True
            loginResponse['csrfToken'] = unicode(csrfToken['csrf_token'])
            return JsonResponse(loginResponse)
        return JsonResponse(loginResponse)

def login2(request):
    if request.method == 'GET':
        loginResponse = {'isLogin' : False, 'csrfToken' : 0,}
        userNameStr = request.GET.get('userName')
        userPwdStr = request.GET.get('userPwd')
        version = request.GET.get('version')
        user = User.objects.filter(userName=userNameStr, userPwd=userPwdStr)
	print >> sys.stderr, "userNameStr:" + str(userNameStr) + ",userPwdStr:" + str(userPwdStr) + ",version:" + str(version)
        isUser = len(user)
        if(isUser):
            #return HttpResponse("login success")
            csrfToken = {}
            csrfToken.update(csrf(request))
            loginResponse['isLogin'] = True
            loginResponse['csrfToken'] = unicode(csrfToken['csrf_token'])
        return JsonResponse(loginResponse)

def register(request):
    if request.method == 'POST':
        userNameStr = request.POST.get('userName')
        userPwdStr = request.POST.get('userPwd')
        user = User.objects.filter(userName=userNameStr, userPwd=userPwdStr)
        isUser = len(user)
        if(isUser):
		return HttpResponse("registered")
	else:
		newuser = User.objects.create(userName=userNameStr, userPwd=userPwdStr)
		newuser.save()
		return HttpResponse("registering");
def register2(request):
    if request.method == 'POST':
        userNameStr = request.POST.get('userName')
        userPwdStr = request.POST.get('userPwd')
        user = User.objects.filter(userName=userNameStr, userPwd=userPwdStr)
        isUser = len(user)
	registerResponse = {'registerStatus' : 'registering'}
        if(isUser):
		registerResponse['registerStatus'] = 'registered'
		return JsonResponse(registerResponse)
	else:
		newuser = User.objects.create(userName=userNameStr, userPwd=userPwdStr)
		newuser.save()
		registerResponse['registerStatus'] = 'registering'
		return JsonResponse(registerResponse)
#def uploadImage(request):
#    if request.method == 'POST':
#        form = UploadFileForm(request.POST, request.FILES)
#        if form.is_valid():
#            #with open('/tmp/%s' % form['title'].value(), 'wb+') as destination:
#            fileUploadName='/var/www/FetchMe/Server/mysite/media/tmp/%s' % request.FILES['fileUpload']
#            with open(fileUploadName, 'wb+') as destination:
#                for chunk in request.FILES['fileUpload'].chunks():
#                    destination.write(chunk)
#            result=caffeRecongination.reconginze('oxfordCatsAndDogs', fileUploadName)
#            return HttpResponse("upload success %s" % result)
#        return HttpResponse("upload failed")
def uploadDevInfo(request):
    if request.method == 'POST':
        version = request.POST.get('version')
	deviceName = request.POST.get('deviceName', '')
	isAgreeOpen = request.POST.get('isAgreeOpen', '')
	requestLockMobileName = request.POST.get('requestLockMobileName', '')
	devinfo = request.POST.get('devinfo', '')
	requestLockOpenFileName = '/var/www/FetchMe/Server/mysite/media/tmp/' + deviceName
	if(isAgreeOpen=='false'):
		os.remove(requestLockOpenFileName)
	else:
		devInfoFileName = '/var/www/FetchMe/Server/mysite/media/tmp/' + deviceName + "_info"
		with open(devInfoFileName, 'wb+') as destination:
			destination.write(devinfo+":"+requestLockMobileName)
	return HttpResponse(deviceName + ":" + isAgreeOpen + ":" + devinfo + ":" + requestLockMobileName)

def downloadDevInfo(request):
    if request.method == 'POST':
        version = request.POST.get('version')
	devInfoFileName = '/var/www/FetchMe/Server/mysite/media/tmp/dev.txt'
	devInfoFile = open(devInfoFileName, 'rb')
	devInfo = devInfoFile.readlines()
	os.remove(devInfoFileName)
	return HttpResponse(devInfo)
def requestLockOpen(request):
    if request.method == 'POST':
        version = request.POST.get('version')
	deviceName = request.POST.get('deviceName', '')
	mobileName = request.POST.get('mobileName', '')
	devInfoFileName = '/var/www/FetchMe/Server/mysite/media/tmp/' + deviceName + "_info"
	requestLockOpenFileName = '/var/www/FetchMe/Server/mysite/media/tmp/' + deviceName
	if(deviceName!=''):
		if os.path.isfile(requestLockOpenFileName):
			if os.path.isfile(devInfoFileName):

				with open(requestLockOpenFileName, 'wb') as destination:
					destination.write(mobileName)

				devInfoFile = open(devInfoFileName, 'rb')
				devInfoFileContent = devInfoFile.readlines()[0].split(":", 1)
				devInfo = devInfoFileContent[0]
				if(devInfoFileContent[1]==mobileName):
					os.remove(devInfoFileName)
					os.remove(requestLockOpenFileName)
					return HttpResponse(devInfo)
				else:
					return HttpResponse('fail')
			else:
				return HttpResponse('fail')
		else:
			if os.path.isfile(requestLockOpenFileName):
				#requestLockOpenFileContent = open(devInfoFileName, 'rb')
				#if(requestLockOpenFileContent!=mobileName):
				with open(requestLockOpenFileName, 'wb') as destination:
					destination.write(mobileName)
			else:
				with open(requestLockOpenFileName, 'wb') as destination:
					destination.write(mobileName)
			return HttpResponse('fail')
	else:
		return HttpResponse('fail')
		
def checkRemoteLockRequest(request):
    if request.method == 'POST':
        version = request.POST.get('version')
	deviceName = request.POST.get('deviceName', '')
	mobileName = request.POST.get('mobileName', '')
	requestLockFileName = '/var/www/FetchMe/Server/mysite/media/tmp/' + deviceName
	requestLockOpenFileName = '/var/www/FetchMe/Server/mysite/media/tmp/' + deviceName + "_pair"
	if os.path.isfile(requestLockOpenFileName):
		requestLockOpenFile = open(requestLockOpenFileName, 'rb')
		rootMobileName = requestLockOpenFile.readlines()
		#return HttpResponse('mobileName=' + mobileName + ",rootMobileName=" + rootMobileName[0])
		if(mobileName == rootMobileName[0]):
			if os.path.isfile(requestLockFileName):
				requestLockFile = open(requestLockFileName, 'rb')
				requestLockMobileName = requestLockFile.readlines()
				if(len(requestLockMobileName)>=1):
					requestLockMobileName = requestLockMobileName[0]
				else:
					requestLockMobileName = ""
				if(requestLockMobileName!=""):
					return HttpResponse('success:' + requestLockMobileName)
				else:
					return HttpResponse('success')
					#return HttpResponse('fail')
			else:
				return HttpResponse('fail')
		else:
			return HttpResponse('fail')
	else:
		return HttpResponse('fail')
def uploadDevAndRootInfo(request):
    if request.method == 'POST':
        version = request.POST.get('version')
	deviceName = request.POST.get('deviceName', '')
	devicePairFileName = '/var/www/FetchMe/Server/mysite/media/tmp/' + deviceName + "_pair"
	mobileName = request.POST.get('mobileName', '')
	with open(devicePairFileName, 'wb+') as destination:
		destination.write(mobileName)
	return HttpResponse('uploadDevAndRootInfo')
#def get_csrfToken(request):
#    csrfToken = {}
#    csrfToken.update(csrf(request))
#    form = NameForm()
#    return HttpResponse("hello %s" % csrfToken['csrf_token'])
